package org.dashboard.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import org.dashboard.bean.AdChart;
import org.dashboard.bean.AdUser;
import org.dashboard.bean.JsonResponse;
import org.dashboard.constant.Constant;
import org.dashboard.service.AdAuthorizationService;
import org.dashboard.service.AdChartService;
import org.dashboard.utils.NameCastTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chart/chart")
public class AdChartController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(AdChartController.class);

    @Value("${permission.charts.filter.enable}")
    private boolean chartFilterEnable;

    @Reference
    private AdChartService adChartService;

    @Reference
    AdAuthorizationService adAuthorizationService;

    @RequestMapping(value = "/get", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public JsonResponse get(HttpServletRequest request) {

        List<AdChart> adCharts = adChartService.selectAdCharts();
        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.setData(NameCastTools.listToListMap(adCharts));

        jsonResponse.setCode(1);
        jsonResponse.setResult("success");
        return jsonResponse;
    }


    @RequestMapping(value = "/search", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public JsonResponse search(HttpServletRequest request) {
        String criteria = request.getParameter("criteria");
        Integer pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));

        PageInfo pageInfo = adChartService.selectAdChartsPaged(criteria, pageIndex, pageSize);

        JsonResponse jsonResponse = new JsonResponse();
        Map<String, Object> map = new HashMap<>();

        map.put("items", NameCastTools.listToListMap(pageInfo.getList()));
        map.put("count", pageInfo.getTotal());

        jsonResponse.setData(map);
        jsonResponse.setCode(1);
        jsonResponse.setResult("success");
        return jsonResponse;
    }


    @RequestMapping(value = "/delete", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public JsonResponse delete(HttpServletRequest request) {
        String chartIds = request.getParameter("chartIds");
        JSONArray jsonArray = (JSONArray) JSON.parse(chartIds);
        ArrayList<Integer> ids = new ArrayList<>();
        if (jsonArray != null) {
            int len = jsonArray.size();
            for (int i = 0; i < len; i++) {
                ids.add(jsonArray.getInteger(i));
            }
        }
        adChartService.deleteByPrimaryKeys(ids);
        return JsonResponse.success();
    }


    @RequestMapping(value = "/add", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public JsonResponse add(HttpServletRequest request) {
        String chartName = request.getParameter("chartName");
        String chartTypeId = request.getParameter("chartTypeId");
        Integer folderId = Integer.parseInt(request.getParameter("folderId"));

        AdChart adChart = new AdChart();
        adChart.setChartName(chartName);
        adChart.setChartTypeId(chartTypeId);
        adChart.setChartFolderId(folderId);
        adChart.setChartData("");

        adChart.setChartId(adChartService.insert(adChart));
        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.setData(NameCastTools.objectToMap(adChart));

        jsonResponse.setCode(1);
        jsonResponse.setResult("success");
        return jsonResponse;
    }


    @RequestMapping(value = "/load", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public JsonResponse load(HttpServletRequest request) {

        Integer chartId = Integer.parseInt(request.getParameter("chartId"));

        if (chartFilterEnable) {
            AdUser adUser = currentAdUser(request);
            if (!currentUserIsManager(request)) {
                boolean flag = adAuthorizationService.checkUserHasResources(adUser.getUserId(), chartId, Constant.RESOURCE_TYPE_CHART);
                if (!flag) {
                    return JsonResponse.failed();
                }
            }
        }

        AdChart adChart = adChartService.selectByPrimaryKey(chartId);

        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.setData(NameCastTools.objectToMap(adChart));

        jsonResponse.setCode(1);
        jsonResponse.setResult("success");
        return jsonResponse;
    }

    @RequestMapping(value = "/update", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public JsonResponse update(HttpServletRequest request) {
        Integer chartId = Integer.parseInt(request.getParameter("chartId"));
        String chartName = request.getParameter("chartName");
        String chartTypeId = request.getParameter("chartTypeId");
        String chartData = request.getParameter("chartData");
        Integer folderId = Integer.parseInt(request.getParameter("folderId"));


        AdChart adChart = new AdChart();
        adChart.setChartId(chartId);
        adChart.setChartName(chartName);
        adChart.setChartTypeId(chartTypeId);
        adChart.setChartFolderId(folderId);
        adChart.setChartData(chartData);

        adChartService.updateByPrimaryKeySelective(adChart);

        adChart = adChartService.selectByPrimaryKey(chartId);
        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.setData(NameCastTools.objectToMap(adChart));

        jsonResponse.setCode(1);
        jsonResponse.setResult("success");
        return jsonResponse;
    }

}
